var idViewFile = 0;

function getUrlParameter(sParam)
{
    var sPageURL = window.location.search.substring(1);
	var sURLVariables = sPageURL.split('&');
    for (var i = 0; i < sURLVariables.length; i++) 
    {
        var sParameterName = sURLVariables[i].split('=');
        if (sParameterName[0] == sParam) 
        {
            return sParameterName[1];
        }
    }
}
function getRootDocuments(folderPath, folderOwner){

	var trashStatus ;
	
	    $.ajax({
	    type: 'GET',
	    url: '/Folder/shareLinkFolder',
	    data: 'path=' + folderPath + '&trashStatus=' + trashStatus + '&userEmail='+folderOwner,
	    datatype:'json',
		assync : 'false',
	    success: function(data)
	    {
	        var json = $.parseJSON(data);
	        var documentContainer = $('#documentBegin');
	        documentContainer.html('');
	        $.each(json, function(index, element) {
	           var document = initDocument(element);
	           documentContainer.append(document).find('div.prod-cnt').fadeIn('slow');
	        });
	        arrangeListGridView();
	        $('a.embed').animatedModal();
	        $('.simulate').click(function (event) {
	        	
	        	var thumbnail = $(event.target);
	        	var simulateNameClick = thumbnail.parent().find('a.embed');
	        	simulateNameClick.click();
	        });
	        
	        $('.foldersimulate').click(function (event) {
	        	
	        	var folder = $(event.target);
	        	var simulateFolderClick = folder.parent().find('a.folderAccess');
	        	simulateFolderClick.click();
	        });
	    },
	    error: function(e)
	    {
	       // alert('Error: ' + e);
	    }
	  });
	    
}

function getAllDocuments(){
	
	var pathFolder = getUrlParameter('path');
	var trashStatus = getUrlParameter('trashStatus');
	var userEmail = $('input[name="folderOwner"]').val();
	if(pathFolder == "undefined"){
		path = "";
	}
	
	if(trashStatus == "undefined"){
		trashStatus = "";
	}
    $.ajax({
    type: 'GET',
    url: '/Folder/shareLinkFolder',
    data: 'path=' + pathFolder + '&trashStatus=' + trashStatus+'&userEmail='+userEmail,
    datatype:'json',
	assync : 'false',
    success: function(data)
    {
        var json = $.parseJSON(data);
        var documentContainer = $('#documentBegin');
        documentContainer.html('');
        $.each(json, function(index, element) {
           var document = initDocument(element);
           documentContainer.append(document).find('div.prod-cnt').fadeIn('slow');
        });
        arrangeListGridView();
        $('a.embed').animatedModal();
        $('.simulate').click(function (event) {
        	
        	var thumbnail = $(event.target);
        	var simulateNameClick = thumbnail.parent().find('a.embed');
        	simulateNameClick.click();
        });
        
        $('.foldersimulate').click(function (event) {
        	
        	var folder = $(event.target);
        	var simulateFolderClick = folder.parent().find('a.folderAccess');
        	simulateFolderClick.click();
        });
        
    },
    error: function(e)
    {
       // alert('Error: ' + e);
    }
    
    
  });
   
   
}

function initDocument(element){

	var document = '';
	var fileName = element.documentName.toString();
	var urlFile = '';
	element.documentCapacity = calculateObjectCapacity(element.documentCapacity);
	document = document.concat('<div class="prod-cnt prod-box shadow cat-1">');
	
	var filePath = element.documentPath;
	var userEmail = element.userEmail;
	
	if(parseInt(element.documentType) == 1){
		urlFile = viewDocument(fileName,filePath,userEmail);
	}
	var documentImages = analyzeImagesType(element.documentType, element.documentName,urlFile);
	document = document.concat(documentImages);
	
	if(parseInt(element.documentType) == 0){
		var folderPath = element.documentPath+'/'+element.documentName;
		document = document.concat('<div class="nameDocument"><div class="fileContent"><p>'
					+'<a href="#" class="folderAccess titleoverflow" onclick="event.preventDefault();openFolder(\''+fileName+','+folderPath+'\')" >'
					+element.documentName+'</a></p></div></div>');
	}
	else{
		document = document.concat('<div class="nameDocument"><div class="fileContent"><p><a contextmenu="'+urlFile+'" href="#animatedModal" id="'+element.documentUrl+'" class="embed titleoverflow" >'
				   +element.documentName+'</a></p></div></div>');
	}
	if(parseInt(element.documentType) == 0){
		document = document.concat('<div class="fileContent-cnt"><div class="fileContent"><div class="infoFile"><p>- -</p></div>');
	} else {
		document = document.concat('<div class="fileContent-cnt"><div class="fileContent"><div class="infoFile"><p>'+element.documentCapacity+'</p></div>');
	}
	
	document = document.concat('<div class="infoFile"><p>'+formatDate(element.modifiedDate)+'</p></div></div></div></div>');

 	return document;
}

window.onpopstate = function(event) {
	  window.location.href = document.location;	
};

function getFileExtension(documentName){
	
	return documentName.split('.').pop();
}

function formatDate (date) {
	  now = new Date(date);
	  year = "" + now.getFullYear();
	  month = "" + (now.getMonth() + 1); if (month.length == 1) { month = "0" + month; }
	  day = "" + now.getDate(); if (day.length == 1) { day = "0" + day; }
	  hour = "" + now.getHours(); if (hour.length == 1) { hour = "0" + hour; }
	  minute = "" + now.getMinutes(); if (minute.length == 1) { minute = "0" + minute; }
	  second = "" + now.getSeconds(); if (second.length == 1) { second = "0" + second; }
	  return year + "-" + month + "-" + day + " " + hour + ":" + minute;
}

function ChangeUrl(page, url) {
    if (typeof (history.pushState) != "undefined") {
        var obj = { Page: page, Url: url };
        history.pushState(obj, obj.Page, obj.Url);
       
    } else {
        alert("Browser does not support HTML5.");
    }
}

$(function () {
    $("#example").click(function () {
       ChangeUrl('example', '?path=taofolder/new');
       document.title = "example";
 	   getAllDocuments();
    });
    

    $("#btn").click(function () {
    	openPhotoSwipe();
     });
    
});

function openFolder(namepathFolder){
	 var documentName = namepathFolder.split(",")[0];
	 var documentPath = namepathFolder.split(",")[1];
	 ChangeUrl(documentName, '?path='+documentPath);
     document.title = documentName;
	 getAllDocuments();
}


function calculateObjectCapacity(capacity){
	var capacity = parseFloat(capacity);
	if(capacity < 1024) capacity = capacity+' B';
	if(capacity >= 1024 && capacity < 1048576) capacity = parseFloat((capacity/1024).toFixed(2))+' KB';
	if(capacity >= 1024*1024 && capacity < 1024*1024*1024) capacity = parseFloat((capacity/1048576).toFixed(2))+' MB';
	if(capacity >= 1024*1024*1024 && capacity < 1024*1024*1024*1024) capacity = parseFloat((capacity/(1024*1024*1024)).toFixed(2))+' GB';
	return capacity;
}


function encode_utf8(string) {
	  return unescape(encodeURIComponent(string));
}

function epochDateTime(){
	var today = new Date(); 
	var expiredDate = new Date(today);
	expiredDate.setDate(today.getDate()+1);
	return parseInt((expiredDate.getTime()-expiredDate.getMilliseconds())/1000);
}

function generateSignature(epochTime,userEmail,filePath,secretKeyId,fileName){
	
	var stringtosign = encode_utf8('GET\n\n\n'+epochTime+'\n/cloudsharingpublic/'+userEmail+'/'+filePath+'/'+fileName);
	var hash = CryptoJS.HmacSHA1(stringtosign, secretKeyId);
	var hashInBase64 = CryptoJS.enc.Base64.stringify(hash);
	var signature = encodeURIComponent(hashInBase64);
	return signature;
}


function viewDocument(fileName,filePath,userEmail){
	var epochTime = parseInt(epochDateTime());
	var AWSAcessKeyId = "AKIAJPGSDIIFNSVSL6AA";
	var secretKeyId = "BzJXJ1hMKQsRfpfxMZlPbJBlUgcKa3DrKx1iJb+J";
	var signature = generateSignature(epochTime,encodeURI(userEmail),encodeURI(filePath),secretKeyId,encodeURI(fileName));
	var urlPresigned = 'https://s3-ap-southeast-1.amazonaws.com/cloudsharingpublic/'+encodeURI(userEmail)+'/'+encodeURI(filePath)+'/'+encodeURI(fileName)
						;//+"?"
						//+"AWSAccessKeyId="+AWSAcessKeyId+"&Expires="+epochTime+"&Signature="+signature;
	return urlPresigned;
}


